package chen.web.blog;

import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import chen.web.blog.Category.Position;
import chen.web.cache.CacheUtils;

/**
 * 缓存博客栏目，每个博客对应一组栏目
 * @author chen
 *
 */
public class CachedCategoryManager extends BaseCategoryManagerProxy {

	private static final String BlogCategoryCatche = "blog-category-cache";
	private static Cache cache;
	
	public CachedCategoryManager(int maxCategoryCountOfPerBlog) {
		super(new CategoryManagerImpl(maxCategoryCountOfPerBlog));
		// TODO Auto-generated constructor stub
		cache = CacheManager.getInstance().getCache(BlogCategoryCatche);
		CacheUtils.storeDescription(cache, "用于缓存博客栏目");
	}

	@Override
	public Category add(Category category) {
		// TODO Auto-generated method stub
		Category result = super.add(category);
		Blog blog = category.getBelong();
		if(blog == null)	throw new NullPointerException();
		cache.remove(blog);
		return result;
	}

	@Override
	public void delete(Category category) {
		// TODO Auto-generated method stub
		super.delete(category);
		Blog blog = category.getBelong();
		if(blog == null)	throw new NullPointerException();
		cache.remove(blog);
	}

	@Override
	public void update(Category category) {
		// TODO Auto-generated method stub
		super.update(category);
		
		Blog blog = category.getBelong();
		if(blog == null)	throw new NullPointerException();
		cache.remove(blog);
	}

	@Override
	public List<Category> getRootCategories(Blog blog) {
		// TODO Auto-generated method stub
		Element elem = cache.get(blog);
		List<Category> result = null;
		if(elem == null){
			result = super.getRootCategories(blog);
			elem = new Element(blog, result);
			cache.put(elem);
		} else {
			result = (List<Category>) elem.getObjectValue();
		}
		return result;
	}

	@Override
	public void move(Category cat, Position pos) {
		// TODO Auto-generated method stub
		super.move(cat, pos);
		Blog blog = cat.getBelong();
		if(blog == null)	throw new NullPointerException();
		cache.remove(blog);
	}

	@Override
	public Category get(Blog belong, int categoryId) {
		// TODO Auto-generated method stub
		List<Category> roots = getRootCategories(belong);
		CategoryManagerImpl impl = (CategoryManagerImpl)cm;
		return impl.find(roots, categoryId);
	}

}
